/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.cms.dm.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.cms.dm.entity.CmsDynamic;
import com.jeeplus.modules.cms.dm.service.CmsDynamicService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 动态表单Controller
 *
 * @author Sawyer
 * @version 2020-11-21
 */
@RestController
@RequestMapping(value = "/cms/dm/cmsDynamic")
public class CmsDynamicController extends BaseController {

    @Autowired
    private CmsDynamicService cmsDynamicService;

    @ModelAttribute
    public CmsDynamic get(@RequestParam(required = false) String id) {
        CmsDynamic entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = cmsDynamicService.get(id);
        }
        if (entity == null) {
            entity = new CmsDynamic();
        }
        return entity;
    }

    /**
     * 动态表单列表数据
     */
    @RequiresPermissions("cms:dm:cmsDynamic:list")
    @GetMapping("list")
    public AjaxJson list(CmsDynamic cmsDynamic, HttpServletRequest request, HttpServletResponse response) {
        Page<CmsDynamic> page = cmsDynamicService.findPage(new Page<CmsDynamic>(request, response), cmsDynamic);
        return AjaxJson.success().put("page", page);
    }

    /**
     * 根据Id获取动态表单数据
     */
    @RequiresPermissions(value = {"cms:dm:cmsDynamic:view", "cms:dm:cmsDynamic:add", "cms:dm:cmsDynamic:edit"}, logical = Logical.OR)
    @GetMapping("queryById")
    public AjaxJson queryById(CmsDynamic cmsDynamic) {
        return AjaxJson.success().put("cmsDynamic", cmsDynamic);
    }

    /**
     * 保存动态表单
     */
    @RequiresPermissions(value = {"cms:dm:cmsDynamic:add", "cms:dm:cmsDynamic:edit"}, logical = Logical.OR)
    @PostMapping("save")
    public AjaxJson save(CmsDynamic cmsDynamic, Model model) throws Exception {
        if (jeePlusProperites.isDemoMode()) {
            return AjaxJson.error("演示模式，不允许操作！");
        }
        String errMsg = beanValidator(cmsDynamic);
        if (StringUtils.isNotBlank(errMsg)) {
            return AjaxJson.error(errMsg);
        }
        //新增或编辑表单保存
        cmsDynamicService.save(cmsDynamic);
        return AjaxJson.success("保存动态表单成功");
    }


    /**
     * 批量删除动态表单
     */
    @RequiresPermissions("cms:dm:cmsDynamic:del")
    @DeleteMapping("delete")
    public AjaxJson delete(String ids) {
        if (jeePlusProperites.isDemoMode()) {
            return AjaxJson.error("演示模式，不允许操作！");
        }
        String[] idArray = ids.split(",");
        for (String id : idArray) {
            cmsDynamicService.delete(new CmsDynamic(id));
        }
        return AjaxJson.success("删除动态表单成功");
    }

    /**
     * 导出excel文件
     */
    @RequiresPermissions("cms:dm:cmsDynamic:export")
    @GetMapping("export")
    public AjaxJson exportFile(CmsDynamic cmsDynamic, HttpServletRequest request, HttpServletResponse response) {
        try {
            String fileName = "动态表单" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            Page<CmsDynamic> page = cmsDynamicService.findPage(new Page<CmsDynamic>(request, response, -1), cmsDynamic);
            new ExportExcel("动态表单", CmsDynamic.class).setDataList(page.getList()).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            return AjaxJson.error("导出动态表单记录失败！失败信息：" + e.getMessage());
        }
    }

    /**
     * 导入Excel数据
     */
    @RequiresPermissions("cms:dm:cmsDynamic:import")
    @PostMapping("import")
    public AjaxJson importFile(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<CmsDynamic> list = ei.getDataList(CmsDynamic.class);
            for (CmsDynamic cmsDynamic : list) {
                try {
                    cmsDynamicService.save(cmsDynamic);
                    successNum++;
                } catch (Exception ex) {
                    failureNum++;
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条动态表单记录。");
            }

            return AjaxJson.success("已成功导入 " + successNum + " 条动态表单记录" + failureMsg);
        } catch (Exception e) {
            return AjaxJson.error("导入动态表单失败！失败信息：" + e.getMessage());
        }
    }

    /**
     * 下载导入动态表单数据模板
     */
    @RequiresPermissions("cms:dm:cmsDynamic:import")
    @GetMapping("import/template")
    public AjaxJson importFileTemplate(HttpServletResponse response) {
        try {
            String fileName = "动态表单数据导入模板.xlsx";
            List<CmsDynamic> list = Lists.newArrayList();
            new ExportExcel("动态表单数据", CmsDynamic.class, 1).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            return AjaxJson.error("导入模板下载失败！失败信息：" + e.getMessage());
        }
    }


}
